import pinia from "@/store/store";
import fetchApi from "@/utils/fetch";
import {
  drawerFormState,
  center,
  helpRef,
  randomClassName,
  dataRes,
  drawerActiveKey,
  operateType,
  scrollRef,
  resetFormState,
  defaultModalVisible,
  defaultModalFormState,
  defaultDrawerInputValidator,
  publish_time,
} from "./store";
import { RuleObject } from "ant-design-vue/es/form/interface";
import { isHasPower } from "@/assets/directives/tools";
import {
  channelOptions,
  countryCodeDict,
  countryCodeMap,
  dicts,
  drawerChannelMap,
  drinkMap,
  educationalMap,
  eyeColorMap,
  hairColorMap,
  intentionMap,
  lockTypeOptions,
  mapListMap,
  merchantUsersMap,
  monthIncomeMap,
  occupationCatesData,
  occupationCatesDict,
  popularOptions,
  punchMap,
  raceMap,
  scoreOptions,
  skinColorMap,
  smokeMap,
  tattooMap,
  transformStatusMap,
  vipOptions,
} from "./dict";
import { fetchList, refreshTable } from ".";
import { Dayjs } from "dayjs";
import { mapKey } from "@/config/globalVar";
import { modalFormState, modalInstance } from "./modal";
import { drawerInstance, drawerLoading, drawerVisible } from "./drawer";
import { tableLoading } from "./table";
import { fetchCurrencyUnit } from "./components/FormComponent/BasicUserInfo";
import { getSelfNodeIcon } from "@system/menu/store";
export const delete_last_string = (string) => {
  if (string.slice(string.length - 1) === "·") return string.slice(0, -1);
  return string;
};
const dictsStore = useDictsStore(pinia);
export const fetchDicts = (dicts = ref<any>({}), params: any = {}) =>
  new Promise(async (resolve) => {
    const res = await userApi.queryDicts(params);
    dicts.value = res.data ?? {};
    dictsStore.setState(res.data ?? {});
    resolve(storeToRefs(dictsStore).getState.value);
  });

export const getCurrentLocation = (callback: any) => {
  if ("geolocation" in navigator) {
    var options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0,
    };
    function success(position: any) {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;
      callback &&
        callback({
          lat: latitude,
          lng: longitude,
        });
    }
    function error(err: any) {
      var errorType = [
        $t("placeholder82") + "app" + $t("placeholder100"),
        $t("placeholder83"),
        $t("placeholder84"),
      ];
    }
    navigator.geolocation.getCurrentPosition(success, error, options);
  }
};

export const handleStrikeLabel = () => (defaultModalVisible[0].value = true);
export const handlePostIssue = () => {
  drawerFormState.images = [];
  clearObjAttr(defaultModalFormState[1]);
  defaultModalFormState[1].images = [];
  defaultModalFormState[1].fileList = [];
  defaultModalFormState[1].auth = 1;
  publish_time.value = $dayjs(getTimeByZone(new Date()));
  defaultModalVisible[1].value = true;
};
export const getLocation = () => {
  clearObjAttr(defaultModalFormState[2]);
  defaultModalVisible[2].value = true;
  nextTick(() =>
    inputSearch(querySelector("." + randomClassName + " input"), handleInput)
  );
};

export const fetchSearchMap = async () => {
  const res = await fetchDicts();
  dicts.value = res;
  channelOptions.value = arrayToOptions(dicts.value.channel, {
    label: "name",
    value: "id",
  });

  vipOptions.value = arrayToOptions(dicts.value.memberType, {
    label: "name",
    value: "level",
  });

  popularOptions.value = arrayToOptions(dicts.value.popularLevel, {
    label: "name",
    value: "level",
  });

  scoreOptions.value = arrayToOptions(dicts.value.scoreLevel, {
    label: "name",
    value: "level",
  });

  lockTypeOptions.value =
    dicts.value?.lockType?.map((item: any, index: any) => ({
      label: item,
      value: index,
    })) ?? [];
  drawerChannelMap.value = dicts.value.channel;
  merchantUsersMap.value = dicts.value.merchantUsers;
  transformStatusMap.value = objectToOptions(dicts.value.conversion);
  intentionMap.value = dicts.value.intention.map((item) => ({
    label: item.name,
    value: item.id,
  }));
  occupationCatesDict.value = arrayToOptions(dicts.value.occupationCates, {
    label: "title_cn",
    value: "id",
  });
  occupationCatesData.value = occupationCatesDict.value.map((item: any) => ({
    ...item,
    isLeaf: false,
  }));
  countryCodeDict.value = objectToOptions(dicts.value.countryCode);
  monthIncomeMap.length = 0;
  dicts.value?.monthIncomeMap.forEach((item) =>
    monthIncomeMap.push({
      label: item.title,
      value: item.value,
    })
  );

  educationalMap.length = 0;
  dicts.value.educationalMap.forEach((item) =>
    educationalMap.push({
      label: item.title,
      value: item.value,
    })
  );
  tattooMap.length = 0;
  dicts.value.tattooMap.forEach((item) =>
    tattooMap.push({
      label: item.title,
      value: item.value,
    })
  );

  smokeMap.length = 0;
  dicts.value.smokeMap.forEach((item) =>
    smokeMap.push({
      label: item.title,
      value: item.value,
    })
  );

  drinkMap.length = 0;
  dicts.value.drinkMap.forEach((item) =>
    drinkMap.push({
      label: item.title,
      value: item.value,
    })
  );

  skinColorMap.length = 0;
  dicts.value.skinColorMap.forEach((item) =>
    skinColorMap.push({
      label: item.title,
      value: item.value,
    })
  );

  hairColorMap.length = 0;
  dicts.value.hairColorMap.forEach((item) =>
    hairColorMap.push({
      label: item.title,
      value: item.value,
    })
  );

  eyeColorMap.length = 0;
  dicts.value.eyeColorMap.forEach((item) =>
    eyeColorMap.push({
      label: item.title,
      value: item.value,
    })
  );

  punchMap.length = 0;
  dicts.value.punchMap.forEach((item) =>
    punchMap.push({
      label: item.title,
      value: item.value,
    })
  );

  raceMap.length = 0;
  dicts.value.raceMap.forEach((item) =>
    raceMap.push({
      label: item.title,
      value: item.value,
    })
  );
  countryCodeMap.value = objectValueToOptions(dicts.value?.countryCode ?? []);
  resetFormState(drawerFormState);
  drawerFormState.mobile_area = countryCodeDict.value[0].value;
};

export const onLoadOccupationCatesData = async (selectedOptions: any) => {
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;
  const res: any = await userApi.getOccupationPosts({
    occupation_cate_id: targetOption.value,
  });
  targetOption.loading = false;
  targetOption.children = (res.data || []).map((item) => ({
    label: item.title_cn,
    value: item.id,
  }));
  occupationCatesData.value = [...occupationCatesData.value];
};

export let password_validate = () => {
  return async (rule: RuleObject, value: string) => {
    if (isEmptyType(value)) {
      defaultDrawerInputValidator[0][0] = true;
      return Promise.reject($t("placeholder16"));
    }

    if (isPassword(value) && value === drawerFormState.password_confirmation) {
      drawerInstance?.value?.refs?.formValidate?.clearValidate?.([
        "password_confirmation",
      ]);

      if (drawerActiveKey.value === 0) {
        defaultDrawerInputValidator[0][0] = false;
        defaultDrawerInputValidator[0][1] = false;
      }

      if (drawerActiveKey.value === 1) {
        defaultDrawerInputValidator[1][0] = false;
        defaultDrawerInputValidator[1][1] = false;
        defaultDrawerInputValidator[1][2] = false;
      }
      return Promise.resolve();
    }

    if (
      !isEmptyType(drawerFormState.password_confirmation) &&
      value !== drawerFormState.password_confirmation
    ) {
      if (drawerActiveKey.value === 0) defaultDrawerInputValidator[0][0] = true;

      if (drawerActiveKey.value === 1) defaultDrawerInputValidator[0][0] = true;
      return Promise.reject($t("placeholder13"));
    }

    if (
      !isEmptyType(drawerFormState.password_confirmation) &&
      value === drawerFormState.password_confirmation
    ) {
      if (drawerActiveKey.value === 0)
        defaultDrawerInputValidator[0][0] = false;

      if (drawerActiveKey.value === 1)
        defaultDrawerInputValidator[1][0] = false;
      return Promise.resolve();
    }

    if (isPassword(value)) {
      if (drawerActiveKey.value === 0)
        defaultDrawerInputValidator[0][0] = false;

      if (drawerActiveKey.value === 1)
        defaultDrawerInputValidator[1][0] = false;
      return Promise.resolve();
    } else {
      if (drawerActiveKey.value === 0) defaultDrawerInputValidator[0][0] = true;
      if (drawerActiveKey.value === 1) defaultDrawerInputValidator[1][0] = true;
      return Promise.reject($t("placeholder6") + "8-13" + $t("placeholder104"));
    }
  };
};
export let password_confirm_validate = () => {
  return async (rule: RuleObject, value: string) => {
    if (isEmptyType(value)) {
      if (drawerActiveKey.value === 0) defaultDrawerInputValidator[0][1] = true;
      if (drawerActiveKey.value === 1) defaultDrawerInputValidator[1][1] = true;
      return Promise.reject($t("placeholder68"));
    }
    if (
      !isEmptyType(drawerFormState.password) &&
      value !== drawerFormState.password
    ) {
      if (drawerActiveKey.value === 0) defaultDrawerInputValidator[0][1] = true;
      if (drawerActiveKey.value === 1) defaultDrawerInputValidator[1][1] = true;
      return Promise.reject($t("placeholder69"));
    }
    if (
      !isEmptyType(drawerFormState.password) &&
      value === drawerFormState.password
    ) {
      if (drawerActiveKey.value === 0)
        defaultDrawerInputValidator[0][1] = false;
      if (drawerActiveKey.value === 1)
        defaultDrawerInputValidator[1][1] = false;
      return Promise.resolve();
    }
    if (isPassword(value)) {
      if (drawerActiveKey.value === 0)
        defaultDrawerInputValidator[0][1] = false;
      if (drawerActiveKey.value === 1)
        defaultDrawerInputValidator[1][1] = false;
      return Promise.resolve();
    } else {
      if (drawerActiveKey.value === 0) defaultDrawerInputValidator[0][1] = true;
      if (drawerActiveKey.value === 1) defaultDrawerInputValidator[1][1] = true;
      return Promise.reject(
        $t("placeholder70") + "8-13" + $t("placeholder114")
      );
    }
  };
};
export const nickname_validate = () => {
  return (rule: any, value: any) => {
    if (!(value?.length >= 2 && value?.length <= 12)) {
      if (operateType.value === "update" || drawerActiveKey.value === 1)
        defaultDrawerInputValidator[1][2] = true;
      return Promise.reject(
        $t("placeholder72") + 2 + $t("base.to") + 12 + $t("base.digit")
      );
    }
    if (operateType.value === "update" || drawerActiveKey.value === 1)
      defaultDrawerInputValidator[1][2] = false;
    return Promise.resolve();
  };
};
export let password_old_verify = ({
  inputValidators,
  index0,
  index1,
  index2,
}: any = {}) => {
  return (rule: RuleObject, value: any) => {
    if (isEmptyType(value)) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder57"));
    }
    if (
      !isEmptyType(modalFormState.password_new) &&
      value === modalFormState.password_new
    ) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder17"));
    }

    if (isPassword(value) && value !== modalFormState.password_new) {
      inputValidators[index0] = false;
      return Promise.resolve();
    }

    if (
      modalFormState.password_new === modalFormState.password_new_confirmation
    ) {
      modalInstance?.value?.refs?.formValidate?.clearValidate?.([
        "password_new",
        "password_new_confirmation",
      ]);
      inputValidators[index1] = false;
      inputValidators[index2] = false;
      return Promise.resolve();
    }

    if (
      modalFormState.password_new !== modalFormState.password_new_confirmation
    ) {
      modalInstance?.value?.refs?.formValidate?.validateFields?.([
        "password_new",
      ]);
      inputValidators[index1] = false;
      inputValidators[index2] = false;
      return Promise.resolve();
    }

    if (
      !isEmptyType(modalFormState.password_new) &&
      value !== modalFormState.password_new
    ) {
      modalInstance?.value?.refs?.formValidate?.clearValidate?.([
        "password_new",
      ]);
      inputValidators[index0] = false;
      inputValidators[index1] = false;
      return Promise.resolve();
    }

    if (isPassword(value)) {
      inputValidators[index0] = false;
      return Promise.resolve();
    } else {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder6") + "8-13" + $t("placeholder104"));
    }
  };
};
export let password_new_verify = ({
  inputValidators,
  index0,
  index1,
}: any = {}) => {
  return async (rule: RuleObject, value: string) => {
    if (isEmptyType(value)) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder0"));
    }
    if (value === modalFormState.password_old) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder17"));
    }
    if (
      !isEmptyType(modalFormState.password_new_confirmation) &&
      value === modalFormState.password_new_confirmation
    ) {
      modalInstance?.value?.refs?.formValidate?.clearValidate?.([
        "password_new_confirmation",
      ]);
      inputValidators[index0] = false;
      inputValidators[index1] = false;
      return Promise.resolve();
    }
    if (
      !isEmptyType(modalFormState.password_new_confirmation) &&
      value !== modalFormState.password_new_confirmation
    ) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder13"));
    }

    if (isPassword(value)) {
      inputValidators[index0] = false;
      return Promise.resolve();
    } else {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder6") + "8-13" + $t("placeholder104"));
    }
  };
};
export let password_new_confirm_verify = ({
  inputValidators,
  index0,
  index1,
}: any = {}) => {
  return async (rule: RuleObject, value: any) => {
    if (isEmptyType(value)) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder14"));
    }
    if (
      !isEmptyType(modalFormState.password_new) &&
      value !== modalFormState.password_new
    ) {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder13"));
    }

    if (
      !isEmptyType(modalFormState.password_new) &&
      modalFormState.password_old === modalFormState.password_new
    ) {
      modalInstance?.value?.refs?.formValidate?.validateFields?.([
        "password_new",
      ]);
      inputValidators[index1] = true;
      return;
    }

    if (
      !isEmptyType(modalFormState.password_new) &&
      value === modalFormState.password_new
    ) {
      modalInstance?.value?.refs?.formValidate?.clearValidate?.([
        "password_new",
      ]);
      inputValidators[index0] = false;
      inputValidators[index1] = false;
      return Promise.resolve();
    }

    if (isPassword(value)) {
      inputValidators[index0] = false;
      return Promise.resolve();
    } else {
      inputValidators[index0] = true;
      return Promise.reject($t("placeholder6") + "8-13" + $t("placeholder104"));
    }
  };
};

export const meassageMap: any = (refreshTable, fetchList) =>
  new Map([
    [
      /^add$/,
      () => {
        message.success($t("base.addSuccess"));
        refreshTable();
      },
    ],
    [
      /^update$|^edit$/,
      () => {
        message.success($t("base.updateSucess"));
        fetchList();
      },
    ],
  ]);
const defineApiMap = (string, number) => {
  const addUser = (formState) =>
    userApi.createPerson({
      mobile_area: formState.mobile_area,
      mobile_number: formState.mobile_number,
      password: formState.password,
      password_confirmation: formState.password_confirmation,
      channel_id: formState.channel_id,
      merchant_uid: formState.merchant_uid,
    });
  const addRobot = (formState) => {
    const _birthday = formState?.birthday
      ? $dayjs(formState?.birthday).format("YYYY-MM-DD")
      : $dayjs(getLastYear(18).getTime() - 1 * 24 * 60 * 60 * 1000).format(
          "YYYY-MM-DD"
        );
    return userApi.createRobot({
      content_position_country_code: formState.content_position_country_code,
      position_country_code: formState.position_country_code,
      mobile_area: formState.mobile_area + "",
      mobile_number: formState.mobile_number,
      password: formState.password,
      password_confirmation: formState.password_confirmation,
      channel_id: formState.channel_id,
      merchant_uid: formState.merchant_uid,
      avatar: formState.avatar,
      account_picture: formState?.account_picture.map((url, index) => ({
        sort: index + 2,
        type: 1,
        url,
      })),
      nickname: formState.nickname,
      sex: formState.sex + "",
      account_type: formState?.account_type ?? [],
      social_account_type: formState.social_account_type,
      social_account: formState.social_account,
      birthday: _birthday,
      lat: !isEmptyType(formState.lat) ? formState.lat + "" : "0",
      long: !isEmptyType(formState.long) ? formState.long + "" : "0",
      tag_ids: [...formState.tag_ids, ...formState.systemIds],
      height:
        formState.height && formState.height != 0
          ? formState.height
          : undefined,
      weight:
        formState.weight && formState.weight != 0
          ? formState.weight
          : undefined,
      vip_level: formState.vip_level,
      score_level: formState.score_level,
      popular_level: formState.popular_level,
      content: formState.content,
      images: formState.images,
      auth: formState.auth,
      is_lock: formState.is_lock,
      country_code: formState.country_code,
      country: formState.country,
      province: formState.province,
      city: formState.city,
      bio: formState?.bio ?? "",
      position: formState.location,
      location: formState.position,
      cup: !isEmptyType(formState.cup) ? formState.cup : undefined,
      video: formState.video,
      intention: formState?.intention?.join(","),
      month_income:
        +formState.month_income != 0 ? formState.month_income : undefined,
      occupation_id: isArray(formState.occupation_id)
        ? formState.occupation_id[formState.occupation_id.length - 1]
        : void 0,
      can_provide: formState.can_provide,
      hair_color: formState.hair_color,
      eye_color: formState.eye_color,
      skin_color: formState.skin_color,
      punch: formState.punch,
      tattoo: formState.tattoo,
      race: formState.race,
      smoke: formState.smoke,
      drink: formState.drink,
      educational: formState.educational,
      verify_video: formState.verify_video,
      verifyFileid: formState.verifyFileid,
      videoFileid: defaultModalFormState[1].videoFileid,
      created_at: !isEmptyType(formState.content)
        ? defaultModalFormState[1].created_at ||
          publish_time.value.format("YYYY-MM-DD HH:mm:ss")
        : undefined,
    });
  };
  const updateUser = (formState) => {
    const _birthday = formState?.birthday
      ? $dayjs(formState?.birthday).format("YYYY-MM-DD")
      : $dayjs(getLastYear(18).getTime() - 1 * 24 * 60 * 60 * 1000).format(
          "YYYY-MM-DD"
        );
    return userApi.updateUser({
      content_position_country_code: formState.content_position_country_code,
      position_country_code: formState.position_country_code,
      editId: formState.uid,
      mobile_area: formState.mobile_area + "",
      mobile_number: formState.mobile_number,
      password: formState.password,
      password_confirmation: formState.password_confirmation,
      avatar: formState.avatar,
      account_picture: formState?.account_picture.map((url, index) => ({
        sort: index + 2,
        type: 1,
        url,
      })),
      nickname: formState.nickname,
      sex: formState.sex + "",
      account_type: formState?.account_type ?? [],
      social_account_type: formState.social_account_type,
      social_account: formState.social_account,
      birthday: _birthday,
      lat: !isEmptyType(formState.lat) ? formState.lat + "" : "0",
      long: !isEmptyType(formState.long) ? formState.long + "" : "0",
      tag_ids: [...formState.tag_ids, ...formState.systemIds],
      dynamicIds: formState.dynamicIds,
      height:
        formState.height && formState.height != 0
          ? formState.height
          : undefined,
      weight:
        formState.weight && formState.weight != 0
          ? formState.weight
          : undefined,
      vip_level: formState.vip_level,
      score_level: formState.score_level,
      popular_level: formState.popular_level,
      images: formState.images,
      content: formState.content,
      auth: formState.auth,
      is_lock: formState.is_lock,
      country_code: formState.country_code,
      country: formState.country,
      province: formState.province,
      city: formState.city,
      channel_id:
        formState.channel_id && formState.channel_id != 0
          ? formState.channel_id
          : undefined,
      merchant_uid:
        formState.merchant_uid && formState.merchant_uid != 0
          ? formState.merchant_uid
          : undefined,
      bio: formState?.bio ?? "",
      position: formState.location,
      location: formState.position,
      cup: !isEmptyType(formState.cup) ? formState.cup : undefined,
      video: formState.video,
      intention: formState?.intention?.join(","),
      month_income:
        +formState.month_income != 0 ? formState.month_income : undefined,
      occupation_id: isArray(formState.occupation_id)
        ? formState.occupation_id[formState.occupation_id.length - 1]
        : formState.occupation_post,
      can_provide: formState.can_provide,
      hair_color: formState.hair_color,
      eye_color: formState.eye_color,
      skin_color: formState.skin_color,
      punch: formState.punch,
      tattoo: formState.tattoo,
      race: formState.race,
      smoke: formState.smoke,
      drink: formState.drink,
      educational: formState.educational,
      verify_video: formState.verify_video,
      verifyFileid: formState.verifyFileid,
      videoFileid: defaultModalFormState[1].videoFileid,
      created_at: !isEmptyType(formState.content)
        ? defaultModalFormState[1].created_at ||
          publish_time.value.format("YYYY-MM-DD HH:mm:ss")
        : undefined,
    });
  };
  const closeDetail: any = () => (drawerVisible.value = false);
  const apiMap = new Map([
    [{ key: "update", state: /[0]/ }, updateUser],
    [{ key: "add", state: /[0]/ }, addUser],
    [{ key: "add", state: /[1]/ }, addRobot],
    [{ key: "view", state: /[0]/ }, closeDetail],
  ]);
  return apiMap;
};
const handleApiTask = async (string, number: any = 0, formState) => {
  try {
    let [, api]: any = [...defineApiMap(string, number)].find(
      ([object]) => object.key == string && object.state.test(number)
    );
    drawerLoading.value = true;
    const result: any = await api(formState);
    if (isBoolean(result) || isEmptyType(result)) return;
    if (result.code != 200) return message.error(result.message);
    drawerVisible.value = false;
    const [, showMessage] = [...meassageMap(refreshTable, fetchList)].find(
      ([key]) => key.test(string)
    );
    showMessage();
  } catch (e: any) {
    message.error(e.message);
  } finally {
    drawerLoading.value = false;
  }
};
export const handleSubmit = () =>
  handleApiTask(operateType.value, drawerActiveKey.value, drawerFormState);
export const GetClickPoint = (point: any) => {
  center.lat = point.latLng.lat();
  center.lng = point.latLng.lng();
};
export const handleChange = (val: any) => {
  const location = JSON.parse(val);
  drawerFormState.lat = location.geometry.location.lat;
  drawerFormState.long = location.geometry.location.lng;
  center.lat = drawerFormState.lat;
  center.lng = drawerFormState.long;
  drawerFormState.country =
    location.address_components.find((item: any) => {
      return item.types.includes("country");
    })?.long_name ?? "";
  drawerFormState.province =
    location.address_components.find((item: any) => {
      return item.types.includes("administrative_area_level_1");
    })?.long_name ?? "";
  drawerFormState.city =
    location.address_components.find((item: any) => {
      return item.types.includes("locality");
    })?.long_name ?? "";
  defaultModalFormState[2].location =
    drawerFormState.country +
    "/" +
    drawerFormState.province +
    "/" +
    drawerFormState.city;
  defaultModalFormState[2].content_position_country_code =
    location.address_components.find((item: any) => {
      return item.types.includes("country");
    })?.short_name ?? "";
};

let timeout: any;
export function fetchAddress() {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  const fake = async () => {
    const res = await fetchApi(
      `/maps/api/place/queryautocomplete/json?key=${mapKey}&input=${defaultModalFormState[2].searchKey}`,
      "GET",
      {}
    );
    let place_ids: string[] = [];
    res.predictions.forEach((item: any) => place_ids.push(item.place_id));
    Promise.all([
      ...place_ids.map((place_id) =>
        fetchApi(
          `/maps/api/geocode/json?place_id=${place_id}&key=${mapKey}`
        ).catch((e) => {
          console.error(e);
        })
      ),
    ])
      .then((result) => {
        mapListMap.value = result?.map((item: any) => {
          return {
            label: item?.results[0]?.formatted_address,
            value: JSON.stringify({
              address_components: item?.results[0]?.address_components?.filter(
                (item: any) => item?.types?.includes("political")
              ),
              geometry: {
                location: item?.results[0]?.geometry?.location,
              },
            }),
          };
        });
      })
      .catch((error: any) => {
        message.error(error.message);
      });
  };
  timeout = setTimeout(fake, 300);
}

export const handleSearch = () => {
  if (!defaultModalFormState[2].searchKey) return;
  fetchAddress();
};

export const handleInput: any = (val: string) => {
  handleInput.timer && clearTimeout(handleInput.timer);
  handleInput.timer = setTimeout(() => {
    mapListMap.value = [];
    defaultModalFormState[2].searchKey = val;
    handleSearch();
  }, 300);
};

export const objectValueToOptions = (obj: any) => {
  const arr = Object.entries(obj);
  const options: any = [];
  for (const [value, label] of arr) options.push({ label, value: label });
  return options;
};

export const getActionOptions = ({ handleAction, record }: any) => {
  const emptyArray: any = [];
  return reactive(
    emptyArray
      .concat(
        isHasPower("userApi.queryDataById")
          ? {
              label: getProxyT("base.detail"),
              value: () => handleAction({ record, type: "view" }),
              icon: renderIcon(getSelfNodeIcon("userApi.queryDataById")),
            }
          : []
      )
      .concat(
        isHasPower("userApi.updateUser")
          ? {
              label: getProxyT("base.edit"),
              value: () => handleAction({ record, type: "update" }),
              icon: renderIcon(getSelfNodeIcon("userApi.updateUser")),
            }
          : []
      )
      .concat(
        isHasPower("userApi.updateStatus")
          ? {
              label: computed(() =>
                +record.is_lock === 0 ? $t("base.disable") : $t("base.enable")
              ),
              value: () => handleAction({ record, type: "update->status" }),
              icon: renderIcon(
                getSelfNodeIcon("userApi.updateStatus")
                  ? record.is_lock === 0
                    ? "icon-qiyong"
                    : "icon-tingyong"
                  : ""
              ),
            }
          : []
      )
      .concat(
        isHasPower("userApi.updateAccountPsd")
          ? {
              label: getProxyT("base.changePsd"),
              value: () => handleAction({ record, type: "update->password" }),
              icon: renderIcon(getSelfNodeIcon("userApi.updateAccountPsd")),
            }
          : []
      )
      .concat(
        isHasPower("userApi.updateAssign")
          ? {
              label: getProxyT("base.dispense"),
              value: () => handleAction({ record, type: "update->dispense" }),
              disabled: !isEmptyType(record.merchant_user),
              icon: renderIcon(getSelfNodeIcon("userApi.updateAssign")),
            }
          : []
      )
  );
};

export const toTimeStamp = (time: any) => {
  if (isString(time)) time = new Date(time).getTime();
  if (isNumber(time) && (time + "").length === 10) time = time * 1000;
  return time;
};

export const deepTreeDataOptions = (treeData: any) => {
  const data =
    treeData?.map((item: any) => {
      return {
        label: item.tag_name,
        value: item.tag_id,
        disableCheckbox: +item.attr_id === 0,
        children:
          item.children && item.children.length
            ? deepTreeDataOptions(item.children)
            : null,
      };
    }) ?? [];
  return data;
};
export const tmp_account_picture = ref<any>([]);
export const tmp_tag_ids = ref<any>([]);
export const fetchDataById = async (record: any) => {
  try {
    tableLoading.value = true;
    const res = await userApi.queryDataById({
      userId: record.uid,
    });
    const { data = {} } = res;
    dataRes.value = data;
    initObjAttr(drawerFormState, {
      memberType: data.memberType,
      conversion: data.conversion,
      video: data.video,
      bio: data.bio,
      places: data.places,
      partyNum: data.partyNum,
      clubNum: data.clubNum,
      friendNum: data.friendNum,
      socialAccountType: data.socialAccountType,
      social_account: data.social_account,
      birthday: data.birthday,
      age: data.age,
      sex: data.sex,
      last_login_time: data.last_login_time,
      country: data.country,
      merchantUser: data.merchantUser,
      origin: data.origin,
      created: data.created,
      mobile_area: data.mobile_area,
      mobile_number: data.mobile_number,
      channel: data.channel,
      constellation: data.constellation,
      is_vip: data.is_vip,
      is_lock: data.is_lock,
      account_type: data?.account_type ?? [],
      avatar: data.avatar,
      account_picture: drawerFormState.account_picture.map(
        (item, index) => data?.account_picture[index]?.url || ""
      ),
      uid: data.uid,
      activedTime: data.activedTime,
      nickname: data.nickname,
      weight: data?.weight && data.weight != 0 ? data.weight : undefined,
      height: data?.height && data.height != 0 ? data.height : undefined,
      popular_level:
        data?.popular_level && data.popular_level != 0
          ? data.popular_level
          : undefined,
      score_level:
        data?.score_level && data.score_level != 0
          ? data.score_level
          : undefined,
      vip_level:
        data?.vip_level && data.vip_level != 0 ? data.vip_level : undefined,
      dynamics: data?.dynamics?.length
        ? data.dynamics.map((item: any) => {
            if (!isEmptyType(item.created_at)) {
              item.created_at = toTimeStamp(item.created_at);
            }
            item.pictures = item.picture;
            return item;
          })
        : [],
      systemIds: data?.accountSystemTag?.map((item: any) => item.tag_id) ?? [],
      tag_ids: data?.accountTag?.map((item: any) => item.tag_id) ?? [],
      accountSystemTag:
        data?.accountSystemTag?.map((item: any) => item.tag_id) ?? [],
      cup: !isEmptyType(data.cup) ? data.cup : undefined,
      intention: data?.intention,
      month_income: +data.month_income != 0 ? data.month_income : undefined,
      occupation_id:
        !isEmptyType(data.occupation_cate) && +data.occupation_cate >= 0
          ? selectDictLabel(occupationCatesData.value, data.occupation_cate) +
            "/" +
            data.occupationCate
          : undefined,
      real_person_status: data.real_person_status,
      can_provide: data.can_provide,
      hair_color:
        data?.hair_color && data.hair_color != 0 ? data.hair_color : undefined,
      eye_color:
        data?.eye_color && data.eye_color != 0 ? data.eye_color : undefined,
      skin_color:
        data?.skin_color && data.skin_color != 0 ? data.skin_color : undefined,
      punch: data?.punch && data.punch != 0 ? data.punch : undefined,
      tattoo: data?.tattoo && data.tattoo != 0 ? data.tattoo : undefined,
      race: data?.race && data.race != 0 ? data.race : undefined,
      smoke: data?.smoke && data.smoke != 0 ? data.smoke : undefined,
      drink: data?.drink && data.drink != 0 ? data.drink : undefined,
      educational:
        data?.educational && data.educational != 0
          ? data.educational
          : undefined,
    });
    tmp_account_picture.value = data.account_picture;
    tmp_tag_ids.value = data.accountTag;
    fetchCurrencyUnit(data.country);
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
export const mobile_validator = async (rule: any, value: string) => {
  if (!value) {
    helpRef.value = computed(() => <i class="fs10">{$t("placeholder32")}</i>);
    return Promise.reject();
  }
  if (isEmptyType(drawerFormState.mobile_area)) {
    helpRef.value = computed(() => <i class="fs10">{$t("placeholder65")}</i>);
    return Promise.reject();
  }
  const res = ref<any>({});
  res.value = await userApi.queryC({
    mobile_area: drawerFormState.mobile_area,
    mobile_number: value,
  });
  if (res.value.code === 200 && res.value.data.flag === 1) {
    helpRef.value = computed(() => <i class="fs10">{$t("placeholder66")}</i>);
    return Promise.reject();
  }
  helpRef.value = null;
  return Promise.resolve();
};

export const set_scrollHeight = () => {
  nextTick(() => {
    const distance = getTopDistance(scrollRef.value);
    scrollRef.value.style.height = `calc(100vh - ${distance}px - 72px)`;
  });
};

export const getStarSign = (date: Dayjs) => {
  const _month = $dayjs(date).month() + 1;
  const _date = $dayjs(date).date();
  const month = String(_month).padStart(2, "0");
  const day = _date;
  switch (month) {
    case "01":
      if (day > 19) {
        return "水瓶座";
      } else return "摩羯座";
    case "02":
      if (day > 18) {
        return "双鱼座";
      } else return "水瓶座";
    case "03":
      if (day > 20) {
        return "白羊座";
      } else return "双鱼座";
    case "04":
      if (day > 19) {
        return "金牛座";
      } else return "白羊座";
    case "05":
      if (day > 20) {
        return "双子座";
      } else return "金牛座";
    case "06":
      if (day > 21) {
        return "巨蟹座";
      } else return "双子座";
    case "07":
      if (day > 22) {
        return "狮子座";
      } else return "巨蟹座";
    case "08":
      if (day > 22) {
        return "处女座";
      } else return "狮子座";
    case "09":
      if (day > 22) {
        return "天秤座";
      } else return "处女座";
    case "10":
      if (day > 23) {
        return "天蝎座";
      } else return "天秤座";
    case "11":
      if (day > 20) {
        return "射手座";
      } else return "天蝎座";
    case "12":
      if (day > 21) {
        return "摩羯座";
      } else return "射手座";
  }
};
